<template>
  <div>
    <title-panel />
    <van-form
      input-align="right"
      error-message-align="right"
      :show-error-message="false"
      show-error
      scroll-to-error
      validate-first
      @failed="onFailed"
      @submit="onSubmit"
    >
      <van-field
        label="销售日期"
        input-align="right"
        required
        is-link
        :value="contentObj.salesDate"
        :rules="[{ required: true, message: '请选择销售日期' }]"
        @click="showDateSelect = true"
      >
      </van-field>
      <van-popup v-model="showDateSelect" position="bottom">
        <van-datetime-picker type="date" @confirm="onConfirm" @cancel="showDateSelect = false" v-model="date" />
      </van-popup>
      <van-field
        label="销售金额（元）"
        v-model="contentObj.salesAmount"
        label-width="40%"
        input-align="right"
        @keydown="valueChange1"
        required
        :rules="[{ required: true, message: '请填写销售金额' }]"
      >
      </van-field>
      <van-field
        label="销售去向"
        @click="inputClick('000')"
        input-align="right"
        is-link
        readonly
        required
        :rules="[{ required: true, message: '请选择销售去向' }]"
        :value="contentObj.enterpriseName"
      >
      </van-field>
      <template v-if="milkStationFlag == 0">
        <van-field
          label="生鲜乳总数量（kg）"
          :rules="[{ required: true, message: '请填写生鲜乳总数量' }]"
          v-model="numbers"
          label-width="40%"
          input-align="right"
          required
          readonly
        >
        </van-field>
      </template>
      <template v-else>
        <van-field
          label="生鲜乳总数量（kg）"
          :rules="[{ required: true, message: '请填写生鲜乳总数量' }]"
          v-model="numbers"
          label-width="40%"
          input-align="right"
          required
        >
        </van-field>
      </template>

      <template v-if="milkStationFlag == 0">
        <title-panel title="自产信息" />
        <van-field
          label="生鲜乳数量（kg）"
          v-model="contentObj.selfFreshMilkTotal"
          label-width="40%"
          input-align="right"
          required
          type="number"
          @keydown="valueChange"
          :rules="[{ required: true, message: '请填写生鲜乳总数量' }]"
        >
        </van-field>
        <div class="flex-between align-items m-r-5">
          <title-panel title="收购明细" />
          <van-button icon="plus" type="primary" native-type="button" class="btn" @click="addItem">新增</van-button>
        </div>
        <div v-for="(item, index) in shouGouDetail" :key="index" style="margin-bottom: 10px">
          <van-field
            input-align="right"
            @click="inputClick(index)"
            required
            readonly
            clickable
            label="生鲜乳来源"
            label-width="10em"
            v-model="item.sourceEnterpriseName"
            is-link
            :rules="[{ required: true, message: '请选择生鲜乳来源' }]"
          >
          </van-field>
          <van-field
            input-align="right"
            required
            readonly
            label="销售批次"
            label-width="10em"
            v-model="item.salesBatchNo"
          />
          <van-field
            input-align="right"
            required
            readonly
            label="生鲜乳总数量"
            type="number"
            label-width="10em"
            v-model="item.freshMilkTotal"
          />
          <van-field input-align="right" center label-width="10em">
            <template #button>
              <van-button color="#999999" native-type="button" plain size="small" @click="deleteItem(index)"
                >删除</van-button
              >
            </template>
          </van-field>
        </div>
        <!-- <template v-if="contentObj.salesStatus == 2">
          <title-panel title="作废信息" />
          <van-cell required title="作废原因" :label="contentObj.reasonForCancellation" />
        </template> -->
      </template>
      <van-button
        block
        color="#37B5B5"
        type="info"
        style="width: 85%; margin: auto; margin-top: 50px"
        size="large"
        native-type="submit"
        :loading="loading"
        loading-text="提交中..."
        >保存</van-button
      >
      <div style="height: 20px"></div>
    </van-form>
  </div>
</template>
<script>
import { Form, Field, Dialog, Toast, DatetimePicker, Picker, Button, Cell, Popup } from 'vant'

import TitlePanel from '@/components/titlePanel'
import { getValue, clearValue } from '@/utils/auth'
import { postHandle, getHandle } from '@/api'
import { setValue } from '../../utils/auth'
export default {
  components: {
    TitlePanel,
    [Form.name]: Form,
    [Field.name]: Field,
    [Picker.name]: Picker,
    [DatetimePicker.name]: DatetimePicker,
    [Button.name]: Button,
    [Popup.name]: Popup,
    [Toast.name]: Toast,
    [Cell.name]: Cell,
    [Dialog.Component.name]: Dialog.Component
  },
  data() {
    return {
      date: new Date(),
      loading: false,
      contentObj: {
        subjectEnterpriseInfo: {},
        whereaboutsEnterpriseId: null,
        whereaboutsEnterpriseName: null,
        salesDate: null,
        salesAmount: null,
        freshMilkTotal: null,
        selfFreshMilkTotal: null,
        salesIds: null
      },
      milKId: getValue('milKId'),
      milkStationFlag: getValue('milkStationFlag'),
      sellDate: '',
      showDateSelect: false,
      shouGouDetail: [],
      numbers: null
    }
  },
  watch: {
    contentObj: {
      handler(val) {
        let num = 0
        this.shouGouDetail.forEach(item => {
          num += Number(item.freshMilkTotal)
        })
        this.numbers = Number(num) + Number(val.selfFreshMilkTotal)
      },
      deep: true
    },
    shouGouDetail: {
      handler(val) {
        let num = 0
        val.forEach(item => {
          num += Number(item.freshMilkTotal)
        })
        num = Number(num) + Number(this.contentObj.selfFreshMilkTotal)
        this.numbers = num
      }
    }
  },
  created() {
    this.$bridge.register('refresh', data => {
      const handle = getValue('milk-object-handle')
      if (handle === 'chooseEnterprise') {
        let milk = getValue('milk-object')
        if (milk) {
          const obj = JSON.parse(milk)
          this.contentObj = Object.assign({}, this.contentObj, obj)
        }
        const enterpriseStr = getValue('enterprise-obj')
        if (enterpriseStr) {
          const enterprise = JSON.parse(enterpriseStr)
          this.contentObj.whereaboutsEnterpriseId = enterprise.id
          this.contentObj.enterpriseName = enterprise.enterpriseName
        }
      }
      if (handle === 'chooseSource') {
        let milk = getValue('milk-object')
        if (milk) {
          const obj = JSON.parse(milk)
          this.contentObj = Object.assign({}, this.contentObj, obj)
        }
        let shouGouDetail = JSON.parse(getValue('milk-shouGouDetail'))
        let index = getValue('milk-index')
        console.log(shouGouDetail)
        shouGouDetail[index] = JSON.parse(getValue('source-obj'))
        this.shouGouDetail = shouGouDetail
      }
    })
    this.initialize()
  },
  methods: {
    inputClick(index) {
      if (index === '000') {
        setValue('milk-object', JSON.stringify(this.contentObj))
        setValue('milk-object-handle', 'chooseEnterprise')
        this.$bridge.call('enterpriseAdd')
      } else {
        setValue('milk-object', JSON.stringify(this.contentObj))
        setValue('milk-object-handle', 'chooseSource')
        setValue('milk-shouGouDetail', JSON.stringify(this.shouGouDetail))
        setValue('milk-index', index)
        this.$bridge.call('milkSource')
      }
    },
    onConfirm(time) {
      this.sellDate = new Date(time).toLocaleDateString()
      this.showDateSelect = false
    },
    initialize() {
      getHandle(`/agri/api/yzbzh/saleInfo/queryDetail/${this.milKId}`).then(res => {
        this.contentObj = res.data
        // this.numbers = this.contentObj.freshMilkTotal
        this.contentObj.whereaboutsEnterpriseId = this.contentObj.subjectEnterpriseInfo.id
        this.contentObj['enterpriseName'] = res.data.subjectEnterpriseInfo.enterpriseName
        this.shouGouDetail = res.data.saleInfoModels
      })
    },
    onFailed(errorInfo) {
      Toast(errorInfo.errors[0].message)
    },
    onSubmit(value) {
      this.loading = true
      this.onSave()
    },
    onSave() {
      let arr = []
      this.shouGouDetail.forEach(item => {
        arr.push(item.id)
      })
      this.contentObj.salesIds = arr.toString()
      // this.contentObj['whereaboutsEnterpriseId'] = this.contentObj.whereaboutsEnterpriseId
      this.contentObj.freshMilkTotal = this.numbers
      postHandle(`/agri/api/yzbzh/saleInfo//update/${this.milKId}`, this.contentObj)
        .then(res => {
          if (res.status === 0) {
            clearValue('milKId')
            setValue('milk-object', null)
            setValue('milk-object-handle', null)
            setValue('enterprise-obj', null)
            setValue('milk-index', null)
            setValue('milk-shouGouDetail', null)
            setValue('source-obj', null)
            this.$toast.success(res.msg)
            this.$bridge.call('base.closePage')
            this.loading = false
          } else {
            this.$toast.fail(res.msg)
            this.loading = false
          }
        })
        .catch(() => {
          this.$toast(res.msg)
          this.loading = false
        })
    },
    deleteItem(index) {
      this.shouGouDetail.splice(index, 1)
    },
    addItem() {
      this.shouGouDetail.push({
        sourceEnterpriseName: '',
        salesBatchNo: '',
        freshMilkTotal: ''
      })
    },
    valueChange(e) {
      e.target.value = e.target.value.match(/^\d*(\.?\d{0,0})/)[0] || null
    },
    valueChange1(e) {
      e.target.value = e.target.value.match(/^\d*(\.?\d{0,1})/)[0] || null
    }
  }
}
</script>
<style lang="scss" scoped>
.flex-between {
  line-height: 2em;
}
::v-deep .van-cell::after {
  border-color: #eeeeee !important;
}
::v-deep .van-cell:last-child {
  border: none !important;
}
.footerImg {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #37b5b5;
  > img {
    width: 22px;
    height: 22px;
  }
}
.shop .bottom {
  position: fixed;
  bottom: 0;
  height: 68px;
  width: 100%;
  box-sizing: border-box;
  background: #ffffff;
  padding: 8px 10px 8px 14px;
  box-shadow: 0px -2px 5px 0px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.addbtn {
  width: 50px;
  height: 24px;
  font-size: 13px;
  padding: 0;
  margin-top: 2px;
}
.border {
  height: 68px;
  width: 1px;
  background: #eeeeee;
}
.btn {
  width: 60px;
  height: 28px;
  border-radius: 4px;
  border: 1px solid #37b5b5;
  font-size: 12px;
  color: #37b5b5;
  background: #eeeeee;
  white-space: nowrap;
  line-height: 28px;
}
</style>
